package tedexis.mercurio.transformers;

import org.apache.log4j.Logger;

import gurulab.maya.common.PhoneAddress;
import gurulab.maya.common.RelativeApplicationAddress;
import gurulab.merlin.core.envelope.Envelope;
import gurulab.merlin.core.router.EnvelopeTransformer;

public class MovilnetTransformer implements EnvelopeTransformer {

	private Logger logger = Logger.getLogger (MovilnetTransformer.class);
	private final String PEER = "movilnet";
	
	public void transform(Envelope envelope) {
		
		if(envelope.getDestinationRoute()!=null && envelope.getDestinationRoute().getPeer().equalsIgnoreCase(PEER)){
			//Va hacia la operadora
			//Transformacion del SMPPOperator
			PhoneAddress phoneAdd = (PhoneAddress)envelope.getDestination ();
			phoneAdd.setCrude (false);
			phoneAdd.setSchema("phone");
			phoneAdd.setNumber ("158"+phoneAdd.getLocal ());
			phoneAdd.setPort("139"+phoneAdd.getPort());
			envelope.setDestination (phoneAdd);
			
		}
		
		if(envelope.getOriginRoute()!=null && envelope.getOriginRoute().getPeer().equalsIgnoreCase(PEER)){
			//Recibe de la operadora
			//Transformacion del SmppEP
			PhoneAddress phoneAdd = (PhoneAddress)envelope.getOrigin();
			phoneAdd.setCrude (true);
			phoneAdd.setSchema("phone");
			phoneAdd.setDomain("58");
			phoneAdd.setPort("416");
			phoneAdd.setLocal(phoneAdd.getNumber().substring(3));//158xxxxxxxx
			envelope.setOrigin(phoneAdd);

			RelativeApplicationAddress relativeApplicationAddress;
			
			RelativeApplicationAddress destAdd = (RelativeApplicationAddress)envelope.getDestination();
            if (destAdd.getPort().substring(0, 3).trim().equalsIgnoreCase("139")) {
                relativeApplicationAddress = new RelativeApplicationAddress(PEER, destAdd.getPort().substring(3));
            } else {
                relativeApplicationAddress = new RelativeApplicationAddress(PEER, destAdd.getPort());
            }
            
            envelope.setDestination(relativeApplicationAddress);
			
		}
        logger.info ("Envelope=" + envelope.toStringNoContent ());
	}

}
